package cn.jetpiece.cloud.dict.app.modular.dict.controller;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import cn.jetpiece.cloud.core.page.PageFactory;
import cn.jetpiece.cloud.core.query.QueryGenerator;
import cn.jetpiece.cloud.core.util.HttpContext;
import cn.jetpiece.cloud.core.util.ResultWrapperUtil;
import cn.jetpiece.cloud.dict.api.DictItemApi;
import cn.jetpiece.cloud.dict.api.model.params.CreateDictItemParam;
import cn.jetpiece.cloud.dict.api.model.params.UpdateDictItemParam;
import cn.jetpiece.cloud.dict.api.model.query.DictItemQuery;
import cn.jetpiece.cloud.dict.api.model.result.DictItemResult;
import cn.jetpiece.cloud.dict.app.modular.dict.entity.DictItem;
import cn.jetpiece.cloud.dict.app.modular.dict.service.IDictItemService;
import cn.jetpiece.cloud.model.page.PageResult;
import cn.jetpiece.cloud.model.response.Result;
import cn.jetpiece.cloud.redis.contants.CacheConstant;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author hancp
 * @version 1.0
 * @description: 字典明细 控制器
 * @date 2021/12/6 11:20
 */
@RestController
@Slf4j
public class DictItemController implements DictItemApi {

    @Autowired
    private IDictItemService dictItemService;

    /**
     * 查询字典数据
     *
     * @param sysDictItemQuery
     * @return
     */
    @Override
    public Result<PageResult<DictItemResult>> queryPageList(DictItemQuery sysDictItemQuery) {
        DictItem sysDictItem = BeanUtil.toBean(sysDictItemQuery, DictItem.class);
        QueryWrapper<DictItem> queryWrapper = QueryGenerator.initQueryWrapper(sysDictItem, HttpContext.getRequestParameters());
        queryWrapper.orderByAsc("sort_order");
        Page<DictItem> page = PageFactory.defaultPage();
        IPage<DictItem> pageList = dictItemService.page(page, queryWrapper);
        return Result.OK(ResultWrapperUtil.wrap(DictItemResult.class, pageList));
    }

    /**
     * 新增
     *
     * @param sysDictItemParam
     * @return
     */
    //@RequiresRoles({"admin"})
    @Override
    @CacheEvict(value = CacheConstant.SYS_DICT_CACHE, allEntries = true)
    public Result<DictItemResult> add(@RequestBody CreateDictItemParam sysDictItemParam) {
        Result<DictItemResult> result = new Result<>();
        try {
            sysDictItemParam.setCreateTime(new Date());
            dictItemService.save(BeanUtil.toBean(sysDictItemParam, DictItem.class));
            result.success("保存成功！");
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            result.error500("操作失败");
        }
        return result;
    }

    /**
     * 编辑
     *
     * @param sysDictItemParam
     * @return
     */
    //@RequiresRoles({"admin"})
    @Override
    @CacheEvict(value = CacheConstant.SYS_DICT_CACHE, allEntries = true)
    public Result<DictItemResult> edit(@RequestBody UpdateDictItemParam sysDictItemParam) {
        Result<DictItemResult> result = new Result<>();
        DictItem dictItem = dictItemService.getById(sysDictItemParam.getId());
        if (dictItem == null) {
            result.error500("未找到对应实体");
        } else {
            sysDictItemParam.setUpdateTime(new Date());
            boolean ok = dictItemService.updateById(BeanUtil.toBean(sysDictItemParam, DictItem.class));
            //TODO 返回false说明什么？
            if (ok) {
                result.success("编辑成功!");
            }
        }
        return result;
    }

    /**
     * 删除字典数据
     *
     * @param ids
     * @return
     */
    //@RequiresRoles({"admin"})
    @Override
    @CacheEvict(value = CacheConstant.SYS_DICT_CACHE, allEntries = true)
    public Result<DictItemResult> delete(String ids) {
        Result<DictItemResult> result = new Result<>();
        if (ids == null || "".equals(ids.trim())) {
            result.error500("参数不识别！");
        } else {
            List<Long> idList = Arrays.asList(ids.split(",")).stream().map(a -> Long.valueOf(a)).collect(Collectors.toList());
            boolean ok = this.dictItemService.removeByIds(idList);
            if (ok) {
                result.success("删除成功!");
            } else {
                result.error500("删除失败!");
            }
        }
        return result;
    }

    /**
     * 字典值重复校验
     *
     * @param sysDictItemQuery
     * @return
     */
    @Override
    public Result<String> doDictItemCheck(DictItemQuery sysDictItemQuery) {
        Result<String> result = new Result<>();
        LambdaQueryWrapper<DictItem> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(DictItem::getItemValue, sysDictItemQuery.getItemValue());
        queryWrapper.eq(DictItem::getDictId, sysDictItemQuery.getDictId());
        if (StrUtil.isNotBlank(sysDictItemQuery.getId())) {
            // 编辑页面校验
            queryWrapper.ne(DictItem::getId, sysDictItemQuery.getId());
        }
        long num = dictItemService.count(queryWrapper);
        if (num == 0L) {
            // 该值可用
            return result.success("该值可用！");
        } else {
            // 该值不可用
            log.info("该值不可用，系统中已存在！");
            return result.error500("该值不可用，系统中已存在！");
        }
    }

}
